package com.xb.loan.encryptor.handler.impl;


import com.xb.loan.encryptor.LotteryException;
import com.xb.loan.encryptor.bean.Head;
import com.xb.loan.encryptor.bean.LotteryBean;
import com.xb.loan.encryptor.bean.request.other.GeneratePartnerKeyReq;
import com.xb.loan.encryptor.bean.response.other.GeneratePartnerKeyRep;
import com.xb.loan.encryptor.handler.BussinessHandler;
import com.xb.loan.encryptor.util.Base64Utils;
import com.xb.loan.encryptor.util.Const;
import com.xb.loan.encryptor.util.RSAUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import java.io.File;
import java.security.interfaces.RSAKey;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;

public class GeneratePartnerKeyHandler implements BussinessHandler {

	private static Log log = LogFactory.getLog(GeneratePartnerKeyHandler.class);
	
	@Override
	public LotteryBean doBussiness(LotteryBean lotteryBean)
			throws LotteryException {
		
		GeneratePartnerKeyReq req = (GeneratePartnerKeyReq) lotteryBean;
		
		Head head = req.getHead();
		
		log.info("GeneratePartnerKeyHandler start generate rsa keyPair,partnerid:" + req.getPartnerId() + ",guid:" + head.getGuid());
		
		RSAKey[] keys = null;
		
		try {
			
			keys = RSAUtils.genKeyPair();
			// 公钥保存路径
			String pubPath = Const.KEY_PATH + File.separatorChar + "partner" + File.separatorChar + req.getPartnerId() + File.separatorChar + "gen" + File.separatorChar + "publicKey.txt";
			// 私钥保存路径
			String priPath = Const.KEY_PATH + File.separatorChar + "partner" + File.separatorChar + req.getPartnerId() + File.separatorChar + "gen" + File.separatorChar + "privateKey.txt";
			// 公钥
			RSAPublicKey publicKey = (RSAPublicKey) keys[0];
			// 私钥
			RSAPrivateKey privateKey = (RSAPrivateKey) keys[1];
			// 公钥base64字符串
			String pubKeyStr = Base64Utils.encode(publicKey.getEncoded());
			// 保存公钥
			Base64Utils.byteArrayToFile(pubKeyStr.getBytes(), pubPath);
			// 保存私钥
			Base64Utils.byteArrayToFile(Base64Utils.encode(privateKey.getEncoded()).getBytes(), priPath);
			
			log.info("GeneratePartnerKeyHandler start generate key end,pubPath:" + pubPath + ",priPath:" + priPath);
			
			return createResponse(req, pubKeyStr);
			
		} catch (Exception e) {
			
			log.error("GeneratePartnerKeyHandler generate rsa keyPair exception,partnerid:" + req.getPartnerId() + ",guid:" + head.getGuid(),e);
			return createResponse(req, null);
		}
	}
	
	private GeneratePartnerKeyRep createResponse(GeneratePartnerKeyReq req, String key){
		
		GeneratePartnerKeyRep rep = new GeneratePartnerKeyRep();
		
		rep.setHead(LotteryBean.createHead("705", req.getHead().getGuid()));
		rep.setPartnerId(req.getPartnerId());
		rep.setPublicKey(key);
		
		return rep;
	}
	
	

}
